from aiogram import Bot
from sqlalchemy.ext.asyncio import AsyncSession

from src.config import Settings
from src.infrastructure.db.services.stats import update_stats
from src.infrastructure.db.services.users import get_users
from src.presentation.tg_bot.services.tg_helpers import broadcast
from src.presentation.tg_bot.worker.exception_handler import exception_handler


@exception_handler
async def notify_users(
    ctx,
    text: str,
    text_eng: str,
    mailing_settings: str,
) -> None:
    bot: Bot = ctx["bot"]
    config: Settings = ctx["config"]
    session: AsyncSession = ctx["session"]

    if mailing_settings == "not_registered":
        users = await get_users(session, registered=False)
    elif mailing_settings == "registered":
        users = await get_users(session, registered=True)
    else:
        users = await get_users(session)

    messages_sent, errors_count = await broadcast(bot, users, text, text_eng)

    await broadcast(
        bot,
        config.tg_bot.admin_ids,
        (
            f"Рассылка закончена\n"
            f"Успешно отправлено сообщений: {messages_sent}\n"
            f"С ошибкой: {errors_count}\n"
            f"Всего пользователей: {len(users)}"
        ),
    )

    await update_stats(session, messages_sent=messages_sent)
